package cn.jinjimi.app.controller;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;

import bolts.Continuation;
import bolts.Task;
import cn.jinjimi.app.AccountManager;
import cn.jinjimi.app.bean.Constants;
import cn.jinjimi.app.controller.event.DataEvent;
import cn.jinjimi.app.controller.event.UploadProfileEvent;
import cn.jinjimi.app.entity.Article;
import cn.jinjimi.app.entity.City;
import cn.jinjimi.app.entity.Companies;
import cn.jinjimi.app.entity.Company;
import cn.jinjimi.app.entity.CompanyType;
import cn.jinjimi.app.entity.Province;
import cn.jinjimi.app.entity.StandTheme;
import cn.jinjimi.app.entity.ThemePreview;
import cn.jinjimi.app.entity.UserProfiles;
import cn.jinjimi.app.entity.UserProfit;
import cn.jinjimi.base.util.GsonUtils;
import cn.jinjimi.base.util.MD5Utils;
import cn.jinjimi.domain.Dispatcher;
import cn.jinjimi.domain.ServiceManager;
import cn.jinjimi.domain.data.dto.BaseResDto;
import cn.jinjimi.domain.data.dto.SiteStatusDTO;
import cn.jinjimi.domain.data.dto.TokenDto;
import cn.jinjimi.domain.data.net.API;
import cn.jinjimi.domain.data.net.AuthService;
import cn.jinjimi.domain.store.AppStore;
import cn.jinjimi.domain.store.ReaderStore;
import cn.jinjimi.domain.store.UserStore;
import retrofit2.Call;
import retrofit2.Response;

/**
 *
 * @author zhenhua
 */
public class UserController extends BaseController {
    private static final String TAG = "UserController";

    /**
     * 账号登录
     * Event LoginEvent
     * E AgentProfiesDTO
     *
     * @param mobile
     * @param password
     */
    public static Task<TokenDto> loginById(final String mobile, final String password) {

        return Task.callInBackground(new Callable<TokenDto>() {
            @Override
            public TokenDto call() throws Exception {
                long time = System.currentTimeMillis();
                Response<TokenDto> res = API.create(AuthService.class)
                                            .login(mobile, getSignedPwd(mobile, password, time), time)
                                            .execute();
                if (res != null && res.isSuccessful()) {
                    TokenDto dto = res.body();
                    if (dto != null) {
                        AccountManager.getInstance().setToken(dto.token);
                        return dto;
                    }
                } else if (res != null && res.errorBody() != null) {
                    return GsonUtils.fromJson(res.errorBody().string(), TokenDto.class);
                }
                return null;
            }
        });
    }

    private static String getSignedPwd(String mobile, String pwd, long time) {
        return MD5Utils.MD5(MD5Utils.MD5(MD5Utils.MD5(pwd)+mobile)+time);
    }

    /**
     * 其他登录，比如验证码，微信登陆
     * Event LoginEvent
     * E AgentProfiesDTO
     *
     * @param mobile
     * @param captcha
     * @param opendId
     * @param unionId
     */
    public static Task<UserProfiles> loginByOther(final String mobile, final String captcha, final String opendId, final String unionId) {

        return Task.callInBackground(new Callable<UserProfiles>() {
            @Override
            public UserProfiles call() throws Exception {
                return null;
            }
        });
    }

    /**
     * 退出登录
     *
     * @return
     */
    public static Task<Void> logout() {
        return Task.callInBackground(new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                AccountManager.getInstance().logout();
                return null;
            }
        });
    }

    /**
     * 重置密码
     * @param mobile
     * @param pwd
     * @param captcha
     * @return
     */
    public static Task<BaseResDto> resetPassword(final String mobile, final String pwd, final String captcha) {
        return Task.callInBackground(new Callable<BaseResDto>() {
            @Override
            public BaseResDto call() throws Exception {
                Response<BaseResDto> res = API.create(AuthService.class)
                                            .resetPassword(mobile, MD5Utils.MD5(pwd), captcha)
                                            .execute();
                if (res != null && res.isSuccessful()) {
                    return res.body();
                } else if (res != null && res.errorBody() != null) {
                    return GsonUtils.fromJson(res.errorBody().string(), BaseResDto.class);
                }
                return null;
            }
        });
    }

    /**
     * 完善资料——设置姓名
     *
     * @param name
     * @return
     */
    public static Task<UserProfiles> perfectDetail(final String name) {
        return Task.callInBackground(new Callable<UserProfiles>() {
            @Override
            public UserProfiles call() throws Exception {
                return ServiceManager.getService(UserStore.class).setRealName(name);
            }
        });
    }

    /**
     * 检查用户的状态,并存入本地
     * Event CheckAgentStatusEvent
     * E SiteStatusDTO
     */
    public static Task<SiteStatusDTO> checkAgentStatus(final int type) {
        return Task.callInBackground(new Callable<SiteStatusDTO>() {
            @Override
            public SiteStatusDTO call() throws Exception {
                return ServiceManager.getService(UserStore.class).getAgentSiteStatus(type);
            }
        });
    }


    /**
     * 更新用户信息
     *
     * @return
     */
    public static Task<UserProfiles> updateUserInfo() {
        return Task.callInBackground(new Callable<UserProfiles>() {
            @Override
            public UserProfiles call() throws Exception {
                return ServiceManager.getService(UserStore.class).getProfile();
            }
        });
    }


    /**
     * 获取我的收藏
     *
     * @param url
     * @param page
     * @param ssoId
     * @return
     */
    public static Task<List<Article>> getCollectArticle(String url, final int page, final String ssoId) {
        return Task.callInBackground(new Callable<List<Article>>() {
            @Override
            public List<Article> call() throws Exception {
                return ServiceManager.getService(ReaderStore.class).getCollects(ssoId, page, Constants.PAGE_LIMIT_20);
            }
        });
    }

    /**
     * 获取分公司接口
     *
     * @param type
     * @return
     */
    public static Task<List<Company>> getCompany(final String type) {
        return Task.callInBackground(new Callable<List<Company>>() {
            @Override
            public List<Company> call() throws Exception {
                return ServiceManager.getService(UserStore.class).getCompanies(type);
            }
        });
    }

    /**
     * 获取总公司接口
     *
     * @return
     */
    public static Task<List<CompanyType>> getCompanyType() {
        return Task.callInBackground(new Callable<List<CompanyType>>() {
            @Override
            public List<CompanyType> call() throws Exception {
                return ServiceManager.getService(UserStore.class).getCompanyTypes();
            }
        });
    }

    /**
     * 修改性别
     *
     * @param gender
     * @return
     */
    public static Task<Boolean> setGender(int gender) {
        HashMap<String, String> data = new HashMap<>();
        data.put("gender", String.valueOf(gender));
        return updateProfile(data, 0);
    }

    /**
     * 修改区域信息
     * Event UploadAreaEvent
     *
     * @param position
     * @param province
     * @param city
     * @return
     */
    public static Task<Boolean> setCity(int position, Province province, City city) {

        HashMap<String, String> data = new HashMap<>(4);
        data.put("province_id", province.id);
        data.put("province_name", province.provinceName);
        data.put("city_id", city.id);
        data.put("city_name", city.cityName);

        return updateProfile(data, position);
    }

    /**
     * 修改姓名
     *
     * @param realName
     * @return
     */
    public static Task<Boolean> setRealName(String realName) {

        HashMap<String, String> data = new HashMap<>();
        data.put("real_name", realName);

        return updateProfile(data, 0);
    }

    /**
     * 修改公司信息
     *
     * @param companyId
     * @param companyName
     * @return
     */
    public static Task<Boolean> setCompany(String companyId, String companyName, int position) {

        HashMap<String, String> data = new HashMap<>();
        data.put("company_id", companyId);
        data.put("company_name", companyName);

        return updateProfile(data, position);
    }

    /**
     * 修改个人简介
     *
     * @param bio
     * @return
     */
    public static Task<Boolean> setPersonalDesc(String bio) {
        HashMap<String, String> data = new HashMap<>();
        data.put("bio", bio);
        return updateProfile(data, 0);
    }

    /**
     * 设置标签
     *
     * @param selectTags
     * @return
     */
    public static Task<Boolean> setTags(List<String> selectTags) {
        JSONObject agent = new JSONObject();
        JSONObject value = new JSONObject();
        JSONArray array = new JSONArray();
        try {
            for (String s : selectTags) {
                array.put(s);
            }
            value.put("tags", array);
            agent.put("agent", value);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return updateProfile(agent, 0);
    }

    /**
     * 修改QQ
     *
     * @param qq
     * @param position
     * @return
     */
    public static Task<Boolean> setQQ(String qq, int position) {
        HashMap<String, String> data = new HashMap<>(1);
        data.put("qq", qq);
        return updateProfile(data, position);
    }

    /**
     * 修改微信
     *
     * @param weixin
     * @param position
     * @return
     */
    public static Task<Boolean> setWeixin(String weixin, int position) {
        final HashMap<String, String> data = new HashMap<>(1);
        data.put("wx_no", weixin);
        return updateProfile(data, position);
    }

    /**
     * 修改用户信息
     *
     * @param data
     * @param position
     * @return
     */
    public static Task<Boolean> updateProfile(final Map<String, String> data, final int position) {

        return Task.callInBackground(new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                boolean result = ServiceManager.getService(UserStore.class).updateProfile(data);
                UploadProfileEvent event = new UploadProfileEvent();
                event.position = position;
                if (result) {
                    event.state = DataEvent.SUCC;
                }
                ServiceManager.getService(Dispatcher.class).dispatch(event);
                return result;
            }
        });
    }

    public static Task<Boolean> updateProfile(final JSONObject jsonObject, final int position) {
        return Task.callInBackground(new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                boolean result = ServiceManager.getService(UserStore.class).updateProfile(jsonObject);
                UploadProfileEvent event = new UploadProfileEvent();
                event.position = position;
                if (result) {
                    event.state = DataEvent.SUCC;
                }
                ServiceManager.getService(Dispatcher.class).dispatch(event);
                return result;
            }
        });
    }

    /**
     * 获取主题接口
     *
     * @return
     */
    public static Task<List<StandTheme.Theme>> getTheme() {
        return Task.callInBackground(new Callable<List<StandTheme.Theme>>() {
            @Override
            public List<StandTheme.Theme> call() throws Exception {
                return ServiceManager.getService(UserStore.class).getThemes();
            }
        });
    }

    /**
     * 获取主题预览图接口
     *
     * @param name
     * @return
     */
    public static Task<ThemePreview> getThemePreview(final String name) {
        return Task.callInBackground(new Callable<ThemePreview>() {
            @Override
            public ThemePreview call() throws Exception {
                return ServiceManager.getService(UserStore.class).getThemePreview(name);
            }
        });
    }

    /**
     * 获取当前使用主题
     *
     * @return
     */
    public static Task<StandTheme.Theme> getCurrentTheme() {
        return Task.callInBackground(new Callable<StandTheme.Theme>() {
            @Override
            public StandTheme.Theme call() throws Exception {
                return ServiceManager.getService(UserStore.class).getCurrentSiteTheme();
            }
        });
    }

    /**
     * 设置应用主题
     *
     * @param id
     * @return
     */
    public static Task<Boolean> activateTheme(final String id) {
        return Task.callInBackground(new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                return ServiceManager.getService(UserStore.class).setSiteTheme(id);
            }
        });
    }

    /**
     * 我的推广费
     *
     * @return
     */
    public static Task<UserProfit> getUserProfit() {
        return Task.callInBackground(new Callable<UserProfit>() {
            @Override
            public UserProfit call() throws Exception {
                return ServiceManager.getService(UserStore.class).getProfit();
            }
        });
    }


    /**
     * 获取所有公司接口
     *
     * @return
     */
    public static Task<Companies> getAllCompanies() {
        return Task.callInBackground(new Callable<Companies>() {
            @Override
            public Companies call() throws Exception {
                return ServiceManager.getService(AppStore.class).getCompanies(AppStore.COMPANY_ALL_TYPE);
            }
        });
    }

    /**
     * 获取热门公司接口
     *
     * @return
     */
    public static Task<Companies> getHotCompanies() {

        return Task.callInBackground(new Callable<Companies>() {
            @Override
            public Companies call() throws Exception {
                return ServiceManager.getService(AppStore.class).getCompanies(AppStore.COMPANY_HOT_TYPE);
            }
        });

    }

    public static Task<TokenDto> login(final String mobile, final String captcha) {
        return Task.callInBackground(new Callable<TokenDto>() {
             @Override
             public TokenDto call() throws Exception {
                boolean isMobileExists = true;

                Response<BaseResDto> res = API.create(AuthService.class)
                        .verificationMobile(mobile)
                        .execute();

                if (res != null && res.isSuccessful()) {
                    BaseResDto dto = res.body();
                    if (dto != null) {
                        isMobileExists = !dto.result;
                    }
                }

                if (isMobileExists) {
                    Response<TokenDto> response  = API.create(AuthService.class).login(mobile, captcha).execute();
                    if (response != null && response.isSuccessful()) {
                        TokenDto dto = response.body();
                        if (dto != null) {
                            AccountManager.getInstance().setToken(dto.token);
                            return dto;
                        }
                    } else if (res != null && res.errorBody() != null) {
                        return GsonUtils.fromJson(res.errorBody().string(), TokenDto.class);
                    }
                }

                return null;
            }
        });
    }

    public static Task<TokenDto> create(final String mobile, final String pwdStr, final String username, final String captcha) {
        return Task.callInBackground(new Callable<TokenDto>() {
            @Override
            public TokenDto call() throws Exception {
                Call<TokenDto> call = API.create(AuthService.class).create(mobile, MD5Utils.MD5(pwdStr), username, captcha);
                Response<TokenDto> res = call.execute();
                if (res != null && res.isSuccessful()) {
                    TokenDto dto = res.body();
                    if (dto != null) {
                        AccountManager.getInstance().setToken(dto.token);
                        return dto;
                    }
                }
                else if (res != null && res.errorBody() != null) {
                    return GsonUtils.fromJson(res.errorBody().string(), TokenDto.class);
                }
                return null;
            }
        });
    }
}
